package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.entity.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
    @Override
    public PageResponseResult listByName(ChannelDto dto) {
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
        this.page(page,queryWrapper);
        PageResponseResult<List> responseResult = new PageResponseResult<List>(page.getCurrent(),(int)page.getSize(),page.getTotal(),page.getRecords());
        return responseResult;
    }

    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        //判断是否为空，为空则添加失败
        if(wmChannel==null || StringUtils.isBlank( wmChannel.getName())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //还需要判断一下新增的数据在数据空中存不存在，若已存在，则返回一个已存在的结果，不存在，则新增成功
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,wmChannel.getName());
        int count = this.count(queryWrapper);
        if(count==0){
            wmChannel.setCreatedTime(new Date());
            this.save(wmChannel);
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
    }
}
